package com.th.apicenter.wifi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.th.apicenter.deduct.entity.ThDeduct;
import com.th.apicenter.mapper.ThDeductMapper;
import com.th.apicenter.tools.Md5Tools;
import com.th.apicenter.tools.OkhttpClient;
import com.th.apicenter.wifi.dto.ThWifiNumDTO;
import com.th.apicenter.wifi.entity.ThWifiData;
import com.th.apicenter.wifi.mapper.ThWifiDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author kay
 * @date 2025/6/25
 * @TODO
 */
@Service
@Slf4j
public class ThWifiDataService {

    @Resource
    private ThWifiDataMapper thWifiDataMapper;

    @Resource
    private ThDeductMapper thDeductMapper;

    public void receive(ThWifiData thWifiData) {
        thWifiDataMapper.insert(thWifiData);
        log.info("接收到wifi的数据：{}", thWifiData);
        ThDeduct thDeduct = thDeductMapper.selectOne(new QueryWrapper<ThDeduct>()
                .eq("account_id", thWifiData.getAccountId())
                .eq("type", "wifi"));

        if (null != thDeduct && thDeduct.getIsTrue() == 1) {
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String date = formatter.format(currentTime);
            String startTime = date + " 00:00:00";
            String endTime = date + " 23:59:59";
            ThWifiNumDTO thWifiNumDTO = thWifiDataMapper.queryNumByDate(thWifiData.getAccountId(), startTime, endTime);
            if (thWifiNumDTO.getPassbackNum() >= 1) {
                BigDecimal x = new BigDecimal(thWifiNumDTO.getPassbackNum()).divide(new BigDecimal(thWifiNumDTO.getTotal()), 2, RoundingMode.CEILING);
                BigDecimal percent = new BigDecimal(thDeduct.getPercent()).divide(new BigDecimal(100), 2, RoundingMode.CEILING);
                if (percent.doubleValue() != 0 && new BigDecimal(1).subtract(x).compareTo(percent) < 0) {
                    log.info("需要扣量，不做操作!");
                } else {
                    Integer passBackWIFI = passBackWIFI(thWifiData);
                    thWifiData.setResultData(String.valueOf(passBackWIFI));
                }
            } else {
                Integer passBackWIFI = passBackWIFI(thWifiData);
                thWifiData.setResultData(String.valueOf(passBackWIFI));
            }
            thWifiData.setUpdateDate(new Date());
            thWifiDataMapper.updateById(thWifiData);
        }
    }

    public int passBackWIFI(ThWifiData thWifiData) {
        Map<String, String> map = new HashMap();
        map.put("clientid", "b6e7fa1c4ce6918fa32bcac38b82365e");
        map.put("sid", thWifiData.getSid() == null ? "" : thWifiData.getSid());
        map.put("stime", thWifiData.getStime() == null ? "" : thWifiData.getStime());
        map.put("cid", thWifiData.getCid() == null ? "" : thWifiData.getCid());
        map.put("os", thWifiData.getOs() == null ? "" : thWifiData.getOs());
        map.put("idfa", thWifiData.getIdfa() == null ? "" : thWifiData.getIdfa());
        map.put("mac", thWifiData.getMac() == null ? "" : thWifiData.getMac());
        map.put("imei", thWifiData.getImei() == null ? "" : thWifiData.getImei());
        map.put("caid", thWifiData.getCaid() == null ? "" : thWifiData.getCaid());
        map.put("caid_version", thWifiData.getCaidVersion() == null ? "" : thWifiData.getCaidVersion());
        map.put("last_caid", thWifiData.getLastCaid() == null ? "" : thWifiData.getLastCaid());
        map.put("last_caid_version", thWifiData.getLastCaidVersion() == null ? "" : thWifiData.getLastCaidVersion());
        map.put("oaid", thWifiData.getOaid() == null ? "" : thWifiData.getOaid());
        map.put("event_amount", "");
        map.put("event_type", "15");
        map.put("ts", String.valueOf(System.currentTimeMillis() / 1000));
        String sign = Md5Tools.signWIFI(map, "Jsl7INqbOUzqgZBh");


        // 使用TreeMap自动按键名升序排序
        Map<String, String> sortedParams = new TreeMap<>(map);

        // 构建键值对字符串
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            if (sb.length() > 0) {
                sb.append('&');
            }
            sb.append(entry.getKey()).append('=').append(entry.getValue());
        }

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("https://c2.wkanx.com/tracking");
        stringBuffer.append("?");
        stringBuffer.append(sb);
        stringBuffer.append("&sign=" + sign + "&extra=actived");

        int code = OkhttpClient.httpGetReturnCode(stringBuffer.toString());
        return code;
    }
}
